﻿using System;
using System.Collections.Generic;
using System.Linq;
using context;
using entities;

namespace DataAccessLibrary.DAL
{
    public class SearchDAO
    {
        private readonly BlueMDataContext _ctx;
        public SearchDAO()
        {
            _ctx = new BlueMDataContext();
        }
        
        public List<vRoomInfo> EnsureRoom(DateTime inDate, DateTime outDate)
        {
            List<vSearchRoom> usearchRooms =
                _ctx.vSearchRooms.Where(p =>
                    (outDate < p.CheckOutDate && outDate > p.CheckInDate) ||
                    (inDate < p.CheckOutDate && inDate > p.CheckInDate) ||
                    (inDate < p.CheckInDate && outDate > p.CheckOutDate)
                    ).OrderBy(p=>p.RoomID).ToList();

            List<vRoomInfo> roomInfos = _ctx.vRoomInfos.ToList();
            foreach (var t in usearchRooms)
            {
                for (var i = 0; i < roomInfos.Count; i++)
                {
                    if (roomInfos[i].RoomID != t.RoomID) continue;
                    roomInfos.RemoveAt(i);
                    break;
                }
            }

            return roomInfos;
        }

       
        public List<vRoomInfo> SearchRoom(DateTime inDate, DateTime outDate, int roomTypeId, int minPrice, int maxPrice, bool view, bool bath, bool balcony)
        {
            try
            {
                List<vRoomInfo> infos = EnsureRoom(inDate, outDate);
                if (roomTypeId > 0)
                    infos = infos.Where(p => p.RoomTypeID == roomTypeId).ToList();
                if (minPrice > 0)
                    infos = infos.Where(p => p.RoomPrice >= minPrice).ToList();
                if (maxPrice > 0)
                    infos = infos.Where(p => p.RoomPrice <= maxPrice).ToList();
                if (view)
                    infos = infos.Where(p => p.View).ToList();
                if (bath)
                    infos = infos.Where(p => p.Bath).ToList();
                if (balcony)
                    infos = infos.Where(P => P.Balcony).ToList();

                return infos;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
